package weixin;

import java.util.ArrayList;
import java.util.List;

import models.Article;
import models.ArticleMulti;
import models.Reply;
import net.ufrog.common.utils.Strings;
import play.Play;
import weixin.WXMessage.Item;

/**
 * 转换器
 * 
 * @author ultrafrog
 * @version 1.0, 2014-12-25
 * @since 1.0
 */
public abstract class Converters {

	public static final String HOST = Play.configuration.getProperty("application.host");
	
	/**
	 * 回复转换
	 * 
	 * @param reply
	 * @param wxmsg
	 */
	public static void replyToMessage(Reply reply, WXMessage wxmsg) {
		if (Strings.equals(reply.type, Reply.Type.TEXT)) {
			wxmsg.msgType = WXMessage.Type.TEXT;
			wxmsg.content = reply.value;
		} else if (Strings.in(reply.type, Reply.Type.SINGLE, Reply.Type.MULTI)) {
			List<Article> articles = new ArrayList<Article>();
			
			if (Strings.equals(reply.type, Reply.Type.SINGLE)) {
				Article article = Article.findById(reply.value);
				articles.add(article);
			} else if (Strings.equals(reply.type, Reply.Type.MULTI)) {
				ArticleMulti articleMulti = ArticleMulti.findById(reply.value);
				articles.addAll(articleMulti.getArticles());
			}
			
			wxmsg.msgType = WXMessage.Type.NEWS;
			wxmsg.articleCount = articles.size();
			wxmsg.articles = new ArrayList<Item>();
			for (Article article: articles) {
				String pic = HOST + article.picUrl.replaceAll("\\\\", "/");
				String url = HOST + "article/" + article.id;
				wxmsg.articles.add(new Item(article.title, article.description, pic, url));
			}
		}
	}
}
